package org.thingsboard.server.service.custom;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.alarm.Alarm;
import org.thingsboard.server.common.data.custom.DeviceGroup;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.custom.DeviceGroupId;
import org.thingsboard.server.dao.custom.DeviceGroupService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.permission.Operation;
import org.thingsboard.server.service.security.permission.Resource;

import static org.thingsboard.server.dao.service.Validator.validateId;

@TbCoreComponent
@Service
@RequiredArgsConstructor
@Slf4j
public class DeviceGroupActionService extends BaseActionService{

    @Autowired
    private DeviceGroupService deviceGroupService;


    public DeviceGroup checkGroupId(DeviceGroupId groupId, Operation operation) throws ThingsboardException {
        try {
            validateId(groupId, "Incorrect alarmId " + groupId);
            //异步：
            DeviceGroup group = deviceGroupService.findGroupByIdAsync(getCurrentUser().getTenantId(), groupId).get();
            //同步：
            //DeviceGroup group = deviceGroupService.findGroupById(getCurrentUser().getTenantId(), groupId);
            checkNotNull(group, "设备分组id [" + groupId + "] 不存在");
            accessControlService.checkPermission(getCurrentUser(), Resource.GROUP, operation, groupId, group);
            return group;
        } catch (Exception e) {
            throw handleException(e, false);
        }
    }
}
